#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import urllib, logging, json
from google.appengine.api import rdbms
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from query import build

INSTANCE_NAME = 'google.com:proppy-sql-test:sqlray'
# CREATE TABLE logs (user VARCHAR(255), scene TEXT, url VARCHAR(1024), entryID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(entryID));

class MainHandler(webapp.RequestHandler):
    def get(self):
        query, values = build(**self.request.params)
        conn = rdbms.connect(instance=INSTANCE_NAME, database='sqlray')
        cursor = conn.cursor()
        cursor.execute(query, values)
        self.response.write(json.dumps([dict((column[0], value)
                                             for column, value in zip(cursor.description, row))
                                        for row in cursor.fetchall()]))

    def post(self):
        user = self.request.get('user')
        scene = self.request.get('scene')
        url = self.request.get('url')
        conn = rdbms.connect(instance=INSTANCE_NAME, database='sqlray')
        cursor = conn.cursor()
        cursor.execute('INSERT INTO logs (user, scene, url) VALUES (%s, %s, %s)', (user, scene, url))
        conn.commit()
        conn.close()
        self.redirect('/')

        
application = webapp.WSGIApplication([('/', MainHandler)],
                                     debug=True)
logging.getLogger().setLevel(logging.DEBUG)
